<template>
  <el-form :model="formData" @submit.prevent="handleSubmit" label-position="top">
    <el-form-item label="行业名称" required>
      <el-autocomplete
        v-model="formData.industryName"
        :fetch-suggestions="queryIndustries"
        placeholder="请输入行业名称"
        clearable
        style="width: 100%"
        :trigger-on-focus="true"
        value-key="name"
        @select="handleSelect"
      />
    </el-form-item>

    <el-form-item>
      <el-button 
        type="primary" 
        @click="handleSubmit"
        :loading="loading"
        :disabled="!formData.industryName"
      >
        <el-icon><Search /></el-icon>
        查询分析
      </el-button>
    </el-form-item>

    <el-alert
      v-if="formData.industryName"
      type="info"
      show-icon
      :closable="false"
    >
      将分析 {{ formData.industryName }} 行业的企业分布、规模、技术水平等情况
    </el-alert>
  </el-form>
</template>

<script>
import { ref, reactive } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { searchIndustries } from '@/api/graphAnalysis';
import { ElMessage } from 'element-plus';

export default {
  name: 'IndustryAnalysisForm',
  components: {
    Search
  },
  props: {
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: ['query'],
  setup(props, { emit }) {
    const formData = reactive({
      industryName: '',
      industryId: null
    });

    const queryIndustries = async (queryString, callback) => {
      try {
        const response = await searchIndustries(queryString || '');
        callback(response.data || []);
      } catch (error) {
        console.error('搜索行业失败:', error);
        ElMessage.error('搜索行业失败，请稍后重试');
        callback([]);
      }
    };

    const handleSelect = (item) => {
      formData.industryId = item.id;
      formData.industryName = item.name;
    };

    const handleSubmit = () => {
      if (!formData.industryName) {
        ElMessage.warning('请先输入行业名称');
        return;
      }
      
      // 发送查询请求
      console.log('发送查询:', formData);
      
      // 如果没有industryId，则使用行业名称作为分析依据
      emit('query', {
        industryId: formData.industryId || null,
        industryName: formData.industryName
      });
    };

    return {
      formData,
      queryIndustries,
      handleSelect,
      handleSubmit
    };
  }
};
</script>

<style scoped>
.el-form {
  width: 100%;
}

.el-button {
  width: 100%;
  margin-top: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

:deep(.el-alert) {
  margin-top: 16px;
}
</style> 